<?php

/**
 * @category   Oos
 * @package    Oos_Auth
 * @license    New BSD License
 */

/**
 * Zend_Http_Client
 */
require_once 'Zend/Http/Client.php';

/**
 * Zend_Http_Client_Exception
 */
require_once 'Zend/Http/Client/Exception.php';

/**
 * Zend_Version
 */
require_once 'Zend/Version.php';


class Oos_WSSE_Login
{
	const DEFAULT_SOURCE = 'php-api-11870';
	
	/**
	 *
	 * @param string $email
	 * @param string $password
	 * @param Zend_Http_Client $client
	 * @param string $source
	 * @return Zend_Http_Client
	 * @throws Zend_Gdata_App_AuthException
	 * @throws Zend_Gdata_App_HttpException
	 */
	public static function getWSSEHeaders($user, $password) {
		$h1 = 'Authorization: WSSE profile="UsernameToken"';
		$nonce = base64_encode(pack("H*", sha1(md5(time()))));
		
		$now = gmdate('Y-m-d\TH:i:s\Z');
		$digest = base64_encode(pack("H*", sha1($nonce . $now . $password)));
		
		$h2 = 'X-WSSE: UsernameToken Username="' . $user . '", ' . 'PasswordDigest="' . $digest . 
				'", Nonce="' . $nonce . '", ' . 'Created="' . $now . '"';
				
		return array($h1, $h2);
	}

	public static function getHttpClient($email, $password, 
		$client = null,
		$source = self::DEFAULT_SOURCE)
	{
		if (!($email && $password)) {
			require_once 'Zend/Gdata/App/AuthException.php';
			throw new Zend_Gdata_App_AuthException('Please set your Google credentials before trying to authenticate');
		}

		if ($client == null) {
			$client = new Zend_Http_Client();
		}
		
		if (!$client instanceof Zend_Http_Client) {
			require_once 'Zend/Gdata/App/HttpException.php';
			throw new Zend_Gdata_App_HttpException('Client is not an instance of Zend_Http_Client.');
		}

		// Build the HTTP client for authentication
		$client->setUri("http://11870.com/api/v1");
		$useragent = $source . ' Zend_Framework_Gdata/' . Zend_Version::VERSION;
		$client->setConfig(array(
				'maxredirects'    => 0,
				'strictredirects' => true,
				'useragent' => $useragent
			)
		);

		$client->setHeaders(self::getWSSEHeaders($email, $password));
		try {
			$response = $client->request('GET');
		} catch (Zend_Http_Client_Exception $e) {
			require_once 'Zend/Gdata/App/HttpException.php';
			throw new Zend_Gdata_App_HttpException($e->getMessage(), $e);
		}

		if ($response->getStatus() == 200) {
			return $client;
		} elseif ($response->getStatus() == 401) {
			require_once 'Zend/Gdata/App/AuthException.php';
			throw new Zend_Gdata_App_AuthException('Authentication with 11870 failed. Reason: "'.$response->getMessage().'"');
		}
	}

}
